package com.example.order.service.impl;

import com.example.order.client.ProductClient;
import com.example.order.dataObject.OrderDetail;
import com.example.order.dataObject.OrderMaster;
import com.example.order.dataObject.ProductInfoOutput;
import com.example.order.dto.CartDTO;
import com.example.order.dto.OrderDTO;
import com.example.order.enums.OrderStatusEnum;
import com.example.order.enums.PayStatusEnum;
import com.example.order.enums.ResultEnum;
import com.example.order.exeception.OrderExeception;
import com.example.order.repository.OrderDetailRepository;
import com.example.order.repository.OrderMasterRepository;
import com.example.order.service.OrderMasterService;
import com.example.order.util.KeyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class OrderMasterServiceImpl implements OrderMasterService {

    @Autowired
    private OrderMasterRepository orderMasterRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private ProductClient productClient;

    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        String uniqueKey = KeyUtil.genUniqueKey();
        BigDecimal orderAmount = BigDecimal.ZERO;
        //        查询商品信息，调用商品服务
        List<String> con = orderDTO.getOderDetaillist().stream().map(OrderDetail::getProductId).collect(Collectors.toList());
        List<ProductInfoOutput> productInfolist = productClient.listForOrder(con);
        //计算总价
        for (OrderDetail orderDetail:orderDTO.getOderDetaillist()  ) {
            for (ProductInfoOutput productInfo:productInfolist  ) {
                if(orderDetail.getProductId().equals(productInfo.getProductId())){
                    orderAmount = productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())).add(orderAmount);
                    BeanUtils.copyProperties(productInfo,orderDetail);
                    orderDetail.setOrderId(uniqueKey);
                    orderDetail.setDetailId(KeyUtil.genUniqueKey());
//                    订单详情入库
                    orderDetailRepository.save(orderDetail);
                }
            }
        }
//        扣库存
        List<CartDTO> list = orderDTO.getOderDetaillist().stream().map(e -> new CartDTO(e.getProductId(), e.getProductQuantity())).collect(Collectors.toList());
        productClient.decreaseStock(list);


        orderDTO.setOrderId(uniqueKey);
        OrderMaster master = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, master);
        master.setOrderAmount(orderAmount);
        master.setOrderStatus(OrderStatusEnum.NEW.getCode());
        master.setPayStatus(PayStatusEnum.WAIT.getCode());
        Date date = new Date();
        master.setCreateTime(date);
        master.setUpdateTime(date);

        orderMasterRepository.save(master);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(String orderId) {
        //先查询订单
        Optional<OrderMaster> orderOptional = orderMasterRepository.findById(orderId);
        if( !orderOptional.isPresent()){
            throw new OrderExeception(ResultEnum.ORDER_NOT_EXIST);
        }
        //查询订单状态
        OrderMaster orderMaster = orderOptional.get();
        if(OrderStatusEnum.NEW.getCode()!=orderMaster.getOrderStatus()){
            throw new OrderExeception(ResultEnum.ORDER_STATUS_EXIST);
        }
        //修改状态
        orderMaster.setOrderStatus(OrderStatusEnum.FINISH.getCode());
        orderMasterRepository.save(orderMaster);

        //查询订单详情
        List<OrderDetail> list = orderDetailRepository.findByOrderId(orderId);
        if(list.isEmpty()){
            throw new OrderExeception(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOderDetaillist(list);
        return orderDTO;
    }
}
